// RMSTranslatorDlg.cpp : implementation file
//

#include "stdafx.h"
#include "RMSTranslator.h"
#include "RMSTranslatorDlg.h"
#include "EditCameraDlg.h"
#include "IPDialog.h"
#include "RecordDlg.h"
#include "PasswordDlg.h"
#include "HomePath.h"
#include "../RMSLib/utility.h"
#include "../Common/RMSLog.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	//{{AFX_DATA(CAboutDlg)
	enum { IDD = IDD_ABOUTBOX };
	CMegaBitmap m_SBLogo;
#if defined _TEC_
	CMegaBitmap m_JNCLogo;
#endif //defined _TEC_
	CString	m_strInfo;
	CString	m_Build;
	//}}AFX_DATA

	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CAboutDlg)
	protected:
	virtual BOOL OnInitDialog();
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL

// Implementation
protected:
	//{{AFX_MSG(CAboutDlg)
	afx_msg BOOL OnEraseBkgnd(CDC* pDC);
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	//{{AFX_DATA_INIT(CAboutDlg)
	m_strInfo = _T(
"Streambox Enterprise Server.\r\n"
"(C) 1999-2006, Streambox Inc.\r\n"
"All rights reserved.\r\n"
"The Program and related user documentation,\r\n"
"if any, are proprietary products of Streambox Inc.,\r\n"
"and are protected under U.S. and international\r\n"
"copyright law. All right, title, and interest\r\n"
"in and to the Program, including associated\r\n"
"intellectual property rights, are and shall\r\n"
"remain with Streambox Inc.\r\n"
);
	m_Build=__DATE__;
	//}}AFX_DATA_INIT
}

BOOL CAboutDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

#if defined _TEC_
	m_JNCLogo.LoadBitmap(IDB_JNCLOGO);
	m_SBLogo.LoadBitmap(IDB_POWERED);
#else //defined _TEC_
	m_SBLogo.LoadBitmap(IDB_LOGO);
#endif //defined _TEC_

	return TRUE;
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAboutDlg)
	DDX_Text(pDX, IDC_INFO, m_strInfo);
	DDX_Text(pDX, IDC_BUILD, m_Build);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
	//{{AFX_MSG_MAP(CAboutDlg)
	ON_WM_ERASEBKGND()
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

BOOL CAboutDlg::OnEraseBkgnd(CDC* pDC)
{
	BOOL bRes = CDialog::OnEraseBkgnd(pDC);

	int x, y;
#if defined _TEC_
	x = 69;
	y = 11;
	m_JNCLogo.DrawTransparent(pDC, x, y, RGB(255, 255, 255));
	x = 164;
	y = 17;
	m_SBLogo.DrawTransparent(pDC, x, y, RGB(192, 192, 192));
#else //defined _TEC_
	x = 50;
	y = 11;
	m_SBLogo.Draw(pDC, x, y);
#endif //defined _TEC_

	return bRes;
}

/////////////////////////////////////////////////////////////////////////////
// CRMSTranslatorDlg dialog

CRMSTranslatorDlg::CRMSTranslatorDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CRMSTranslatorDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CRMSTranslatorDlg)
	m_ReflectorIP = _T("");
	m_ServerIP	  = _T("");
	m_ServerPort  =_T("");
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);

	m_ReflectorIP = CString( GetIPStr(REGISTRY_LoadInt(KEY_REFLECTOR_IP,GetLocalHostIP(0))) );
	m_ServerIP	  = CString( GetIPStr(REGISTRY_LoadInt(KEY_SERVER_IP,GetLocalHostIP(0))) );
	m_ServerPort.Format("%d",REGISTRY_LoadInt(KEY_SERVER_PORT,777));
	initHomePath();

	m_Server.AllocateData(MAX_CAMERAS);
}

void CRMSTranslatorDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CRMSTranslatorDlg)
	DDX_Control(pDX, IDC_LISTENCODERS, m_listEncoders);
	DDX_Control(pDX, IDC_LISTCONNECTION, m_listConnections);
	DDX_Text(pDX, IDC_REFLECTOR_IP, m_ReflectorIP);
	DDX_Text(pDX, IDC_SERVER_IP, m_ServerIP);
	DDX_Text(pDX, IDC_SERVER_PORT, m_ServerPort);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CRMSTranslatorDlg, CDialog)
	//{{AFX_MSG_MAP(CRMSTranslatorDlg)
	ON_WM_ERASEBKGND()
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_CHANGE_SERVER, OnChangeServer)
	ON_BN_CLICKED(IDC_CHANGE_REFLECTOR, OnChangeReflector)
	ON_WM_TIMER()
	ON_COMMAND(ID_ABOUT, OnAbout)
	ON_COMMAND(ID_EXIT, OnExit)
	ON_COMMAND(ID_EDITCAMERAINFORMATION, OnEditCameraInformation)
	ON_BN_CLICKED(IDC_RECORD, OnRecord)
	ON_COMMAND(ID_SETPASSWORD, OnSetPassword)
	ON_COMMAND(ID_SET_HOME_PATH, OnSetHomePath)
	ON_COMMAND(ID_HELP, OnHelp)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CRMSTranslatorDlg message handlers

BOOL CRMSTranslatorDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

#if defined _TEC_
	m_JNCLogo.LoadBitmap(IDB_JNCLOGO);
	m_SBLogo.LoadBitmap(IDB_POWERED);
#else //defined _TEC_
	m_SBLogo.LoadBitmap(IDB_LOGO);
#endif //defined _TEC_

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	
	m_Server.SetRecordState(FALSE);
	m_Server.LoadInfo();
	m_Server.LoadPassword();
	m_Server.SetReflectorIP(static_cast<LPCTSTR>(m_ReflectorIP));

	bool bCorrectIP = false;
	int i = 0;
	while (i<100) {
		int ip=GetLocalHostIP(i++);
		if (ip==0) break;
		if(strcmp(GetIPStr(ip),static_cast<LPCTSTR>(m_ServerIP)) == 0)
		{
			bCorrectIP = true;
			break;
		}
	}
	if(!bCorrectIP)
	{
		m_ServerIP = GetIPStr(INADDR_ANY);
		REGISTRY_SaveInt(KEY_SERVER_IP,INADDR_ANY);
	}

	m_Server.ListenInit(static_cast<LPCTSTR>(m_ServerIP), static_cast<LPCTSTR>(m_ServerPort));
	m_Server.SetOutListBox(&m_listConnections, &m_listEncoders);
#ifdef _CYCLIC_BUFFER_
	m_Server.SetRecordCycle(2);
	m_Server.InitStorage();
#endif


	if(!m_Server.ListenStart()) {
		m_ServerIP="127.0.0.1";
		UpdateData(FALSE);
		m_Server.ListenInit(static_cast<LPCTSTR>(m_ServerIP), static_cast<LPCTSTR>(m_ServerPort));
		if(!m_Server.ListenStart())
		{
			MessageBox("Unable to start server.","Error",MB_OK | MB_ICONERROR);
			EndDialog(0);
			return FALSE;
		}
	}

	SetTimer(1, 1000, 0);
#ifdef _CYCLIC_BUFFER_
	SetTimer(2,2000,0);
#endif

	
	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CRMSTranslatorDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CRMSTranslatorDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

BOOL CRMSTranslatorDlg::OnEraseBkgnd(CDC* pDC)
{
	BOOL bRes = CDialog::OnEraseBkgnd(pDC);

	int x, y;
#if defined _TEC_
	x = 69;
	y = 6;
	m_JNCLogo.DrawTransparent(pDC, x, y, RGB(255, 255, 255));
	x = 164;
	y = 12;
	m_SBLogo.DrawTransparent(pDC, x, y, RGB(192, 192, 192));
#else //defined _TEC_
	x = 57;
	y = 11;
	m_SBLogo.Draw(pDC, x, y);
#endif //defined _TEC_

	return bRes;
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CRMSTranslatorDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

void CRMSTranslatorDlg::OnChangeServer() 
{
	// TODO: Add your control notification handler code here
	UpdateData(TRUE);

	CIPDialog dlg("Server IP address and port",
				   REGISTRY_LoadInt(KEY_SERVER_IP,0),REGISTRY_LoadInt(KEY_SERVER_PORT,777));
	int nResponse = dlg.DoModal();
	if (nResponse == IDOK) {
		// save new values
		REGISTRY_SaveInt(KEY_SERVER_IP,dlg.IP);
		REGISTRY_SaveInt(KEY_SERVER_PORT,dlg.m_Port);

		// read int back
		m_ServerIP	  = CString( GetIPStr(REGISTRY_LoadInt(KEY_SERVER_IP,GetLocalHostIP(0))) );
		m_ServerPort.Format("%d",REGISTRY_LoadInt(KEY_SERVER_PORT,777));

		m_Server.ListenStop();

		m_Server.ListenInit(static_cast<LPCTSTR>(m_ServerIP), static_cast<LPCTSTR>(m_ServerPort));

		if(!m_Server.ListenStart())
		{
			MessageBox("Unable to start Server","RMS Reflector",MB_OK | MB_ICONWARNING);
			EndDialog(IDOK);
		}

		UpdateData(FALSE);	
	}
}

void CRMSTranslatorDlg::OnChangeReflector() 
{
	UpdateData(TRUE);

	CIPDialog dlg(  "Server internal IP address",
					REGISTRY_LoadInt(KEY_REFLECTOR_IP,0),0);
	int nResponse = dlg.DoModal();
	if (nResponse == IDOK) {
		// save new values
		REGISTRY_SaveInt(KEY_REFLECTOR_IP,dlg.IP);
		// read int back
		m_ReflectorIP = CString( GetIPStr(REGISTRY_LoadInt(KEY_REFLECTOR_IP,GetLocalHostIP(0))) );

		UpdateData(FALSE);

		m_Server.SetReflectorIP(static_cast<LPCTSTR>(m_ReflectorIP));
	}
	
}

void CRMSTranslatorDlg::OnTimer(UINT nIDEvent) 
{
	switch(nIDEvent)
	{
	case	1:
		m_Server.DeletePassiveClients();
		m_Server.DeletePassiveCameras();
		m_Server.UpdateListBox();
		break;
#ifdef _CYCLIC_BUFFER_
	case 2:
		m_Server.CheckDeleteOldFiles();
		break;
#endif //def _CYCLIC_BUFFER_
	}
		
	CDialog::OnTimer(nIDEvent);
}

BOOL CRMSTranslatorDlg::DestroyWindow() 
{
	m_Server.Close();
	
	return CDialog::DestroyWindow();
}

void CRMSTranslatorDlg::OnAbout() 
{
	CAboutDlg dlgAbout;
	dlgAbout.DoModal();
}

void CRMSTranslatorDlg::OnExit() 
{
	EndDialog(0);
}

void CRMSTranslatorDlg::OnEditCameraInformation() 
{
	CEditCameraDlg dlg;
	dlg.pBaseServer = &m_Server;
	dlg.DoModal();
}

void CRMSTranslatorDlg::OnRecord() 
{
	if(m_Server.GetRecordState())
	{
		m_Server.SetRecordState(FALSE);
		SetDlgItemText(IDC_RECORD,"Record");
		m_Server.CloseRecordDlg();
	}
	else
	{
		m_Server.SetRecordState(TRUE);
		SetDlgItemText(IDC_RECORD,"Stop");
		if(!m_Server.OpenRecordDlg(this))
		{
			TRACE0("Unable to create status window");
			return;
		}
	}	
}

void CRMSTranslatorDlg::OnSetPassword() 
{
	CPasswordDlg dlg;
	if(dlg.DoModal() == IDOK)
	{
		m_Server.SetPassword(static_cast<LPCTSTR>(dlg.m_strPassword));
		m_Server.SavePassword();
	}
}

void CRMSTranslatorDlg::initHomePath()
{
	TCHAR buf[256];
	m_homePath = _T("");
	if(REGISTRY_LoadString(KEY_HOME_PATH, buf, sizeof(buf)))
	{
		m_homePath = buf;
	}
	else
	{
		//saveHomePath(_T("c:"));
		saveHomePath(_T("."));
	}
}

LPCTSTR CRMSTranslatorDlg::getHomePath()
{
	return m_homePath;
}

void CRMSTranslatorDlg::saveHomePath(LPCTSTR home)
{
	m_homePath = home;
	REGISTRY_SaveString(KEY_HOME_PATH, home);
}

void CRMSTranslatorDlg::OnSetHomePath()
{
	CHomePath dlg;
	dlg.m_homePath = getHomePath();
	if(dlg.DoModal() == IDOK)
	{
		saveHomePath(dlg.m_homePath);
//		ReadAddressBook(); // re-read address book
	}
}

void CRMSTranslatorDlg::OnHelp() 
{
	if((int)(ShellExecute(NULL,NULL,"SEESGuide.pdf",NULL,NULL,SW_SHOW))<=32)
	{
		MessageBox("Unable to open help file. SEESGuide.pdf","Warning",MB_OK|MB_ICONWARNING);
	}
}
